package com.jt.www.admin.market.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.jt.www.admin.market.service.CommissionService;
import com.jt.www.admin.market.service.InsidePerformanceService;
import com.jt.www.admin.market.service.TeamService;
import com.jt.www.admin.user.service.UserService;
import com.jt.www.dao.mapper.market.*;
import com.jt.www.dao.mapper.registerCustomer.RegisterCustomerMapper;
import com.jt.www.domain.bo.CommissionBO;
import com.jt.www.domain.bo.MarketerUserRoleBO;
import com.jt.www.domain.enums.common.IsDeletedEnum;
import com.jt.www.domain.enums.common.IsOrNotEnum;
import com.jt.www.domain.enums.common.PushStatusEnum;
import com.jt.www.domain.enums.common.YesOrNoEnum;
import com.jt.www.domain.enums.pc.MarketerRoleEnum;
import com.jt.www.domain.enums.pc.MarketerUserRoleEnum;
import com.jt.www.domain.enums.wxb.PerformancePolicyStatusEnum;
import com.jt.www.domain.enums.wxb.SpecialTypeEnum;
import com.jt.www.domain.po.*;
import com.jt.www.domain.qo.CommissionPushQO;
import com.jt.www.domain.qo.CommissionQO;
import com.jt.www.domain.qo.EndorsementsEduQueryVO;
import com.jt.www.domain.qo.TeamMembersQO;
import com.jt.www.domain.vo.*;
import com.jt.www.model.param.endorse.AppDetailProParam;
import com.jt.www.model.registerCustomer.RegisterCustomer;
import com.jt.www.model.registerCustomer.vo.JtBranchInfoVo;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.model.vo.endorse.AppDetailProVo;
import com.jt.www.model.vo.sdCheck.InsuredForProVO;
import com.jt.www.remote.PolClient;
import com.jt.www.remote.UserClient;
import com.jt.www.remote.ins.InsClient;
import com.jt.www.util.DateUtils;
import com.jt.www.util.JsonUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 佣金相关
 * Created by shaoyn on 2020/04/10.
 */
@Service
public class CommissionServiceImpl implements CommissionService {

    public static final Logger log = LoggerFactory.getLogger(CommissionServiceImpl.class);


    @Autowired
    private CommissionMapper commissionMapper;
    @Autowired
    private CommissionProductMapper commissionProductMapper;
    @Autowired
    private CommissionRoleMapper commissionRoleMapper;
    @Autowired
    private CommissionPushMapper commissionPushMapper;
    @Autowired
    private MarketerInfoMapper marketerInfoMapper;
    @Autowired
    private TeamFounderMapper teamFounderMapper;
    @Autowired
    private TeamService teamService;
    @Autowired
    private InsClient insClient;
    @Autowired
    private PolClient polClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private RegisterCustomerMapper registerCustomerMapper;
    @Autowired
    private InsidePerformanceService insidePerformanceService;
    @Autowired
    private InsidePerformanceMapper insidePerformanceMapper;

    @Autowired
    private UserService userService;

    @Override
    @Transactional
    public int saveCommission(CommissionBO commissionBO) throws Exception {
        //插入佣金产品配置
        CommissionProduct commissionProduct = commissionBO.getCommissionProduct();
        //查询该产品是否配置过
        CommissionProduct commissionProductQo = new CommissionProduct();
        commissionProductQo.setProductCode(commissionProduct.getProductCode());
        commissionProductQo.setIsDeleted(IsDeletedEnum.NO.getValue());
        if (commissionProductMapper.select(commissionProductQo).size() > 0) {
            log.info("产品编码为：{}，的产品已经配置佣金相关信息。", commissionProduct.getProductCode());
            throw new Exception("产品:" + commissionProduct.getProductName() + "已经配置佣金相关信息。");
        }

        int n = commissionProductMapper.insertSelective(commissionProduct);
        if (n == 1) {
            long comProdId = commissionProduct.getId();
            for (CommissionRole commissionRole : commissionBO.getCommissionRoles()) {
                commissionRole.setComProdId(comProdId);
                commissionRoleMapper.insertSelective(commissionRole);
            }
        }
        return 1;
    }

    @Override
    @Transactional
    public int updateCommission(CommissionBO commissionBO) {
        CommissionProduct commissionProduct = commissionBO.getCommissionProduct();
        commissionProduct.setUpdateTime(new Date());
        int n = commissionProductMapper.updateByPrimaryKeySelective(commissionProduct);
        for (CommissionRole commissionRole : commissionBO.getCommissionRoles()) {
            commissionRole.setUpdateTime(new Date());
            n += commissionRoleMapper.updateByPrimaryKeySelective(commissionRole);
        }
        return n;
    }

    @Override
    public ResponseEntity queryCommission(CommissionQO commissionQO) {

        int total = commissionMapper.selectCommissionListCount(commissionQO);
        if (total < 0) {
            return GenericListResponse.listAndCount(Lists.newArrayList(), 0L);
        }
        return GenericListResponse.listAndCount(commissionMapper.selectCommissionList(commissionQO), total);
    }

    @Override
    public boolean isHasCommission(String productCode) {
        CommissionQO commissionQO = new CommissionQO();
        commissionQO.setProductCode(productCode);
        return commissionMapper.selectCommissionListCount(commissionQO) > 0;
    }

    @Override
    public int saveCommissionPush(CommissionPush commissionPush) {
        commissionPush.setPushStatus(PushStatusEnum.DEFAULT.getCode());
        return commissionPushMapper.insertSelective(commissionPush);
    }

    @Override
    public CommissionPush createInsCommissionPush(String logId, String appCode) {
        //查询投保详情
        AppDetailProVo appDetailProVo = searchAppDetailPro(appCode);
        if (null == appDetailProVo) {
            //查询失败 不做处理
            log.error("{} 投保单号：{}查询投保详情失败，不做佣金计算。", logId, appCode);
            return null;
        }
        //通过保单号校验是否重复
        String policyNo = appDetailProVo.getPolicyNo();
        CommissionPush select = new CommissionPush();
        select.setPolicyNo(policyNo);
        select.setIsDeleted(IsDeletedEnum.NO.getValue());
        if (commissionPushMapper.selectCount(select) > 0) {
            log.error("{} 投保单号：{}，对应的保单:{}已有佣金记录，不做佣金计算。", logId, appCode, policyNo);
            return null;
        }
        //计算及生产佣金推送信息
        CommissionPush commissionPush = calCommissionCreatePush(logId, appDetailProVo, null,
                new BigDecimal(appDetailProVo.getPrem()), appDetailProVo.getIssueDate());
        if (null != commissionPush) {
            //保存推送信息
            saveCommissionPush(commissionPush);
        }
        return commissionPush;
    }

    @Override
    public CommissionPush createPolCommissionPush(String logId, String applyNo, String endorsementNo, String userCode) {

        String branchCodes = userService.getBranchCodes(logId, userCode);

        EndorsementsEduQueryVO endorsementsEduQueryVO = new EndorsementsEduQueryVO();
        endorsementsEduQueryVO.setApplyNo(applyNo);
        endorsementsEduQueryVO.setEndorsementsNo(endorsementNo);
        endorsementsEduQueryVO.setUserCode(userCode);
        endorsementsEduQueryVO.setChannelCode("edu");
        endorsementsEduQueryVO.setBranchScope(branchCodes);
        GenericListResponse<EduPolicyVO> eduPolicyVOGenericListResponse;
        EduPolicyVO eduPolicyVO = null;
        try {
            eduPolicyVOGenericListResponse = polClient.queryEduEndorsementsInfoList(endorsementsEduQueryVO);
            //通过批单号及批单申请号查询只会出现一个批单信息
            eduPolicyVO = eduPolicyVOGenericListResponse.getList().get(0);
        } catch (Exception e) {
            log.error("{} 批单查询失败! 入参：{}", logId, JsonUtils.toJson(endorsementsEduQueryVO));
        }
        //如果批单信息为空 不做处理
        if (null == eduPolicyVO) {
            log.error("{} 批单查询无结果! 入参：{}", logId, JsonUtils.toJson(endorsementsEduQueryVO));
            return null;
        }
        //查询投保详情信息
        AppDetailProVo appDetailProVo = searchAppDetailPro(eduPolicyVO.getAppCode());
        if (null == appDetailProVo) {
            //查询失败 不做处理
            log.error("{}  投保单号{}，查询投保详情，查询无结果! 入参：{}", logId, eduPolicyVO.getAppCode());
            return null;
        }
        //计算及生产佣金推送信息
        CommissionPush commissionPush = calCommissionCreatePush(logId, appDetailProVo, endorsementNo,
                new BigDecimal(eduPolicyVO.getBatchPremium()), DateUtils.str2Date(eduPolicyVO.getValidDate(), DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        if (null != commissionPush) {
            //保存推送信息
            saveCommissionPush(commissionPush);
        }
        return commissionPush;
    }

    @Override
    public ResponseEntity queryCommissionDetails(Long id) {
        //查询佣金产品配置表
        CommissionProduct commissionProductQo = new CommissionProduct();
        commissionProductQo.setId(id);
        commissionProductQo.setIsDeleted(IsDeletedEnum.NO.getValue());

        CommissionProduct commissionProduct = commissionProductMapper.selectOne(commissionProductQo);
        if (null == commissionProduct) {
            return GenericDataResponse.errorWithMsg("无查询信息!");
        }
        //查询佣金角色配置表
        CommissionRole commissionRole = new CommissionRole();
        commissionRole.setComProdId(id);
        commissionRole.setIsDeleted(IsDeletedEnum.NO.getValue());
        List<CommissionRole> commissionRoles = commissionRoleMapper.select(commissionRole);

        return GenericDataResponse.okWithData(new CommissionBO(commissionProduct, commissionRoles));
    }

    @Override
    @Transactional
    public int deleteCommission(Long id) {
        //查询佣金产品配置表
        CommissionProduct commissionProductQo = new CommissionProduct();
        commissionProductQo.setId(id);
        commissionProductQo.setIsDeleted(IsDeletedEnum.IS.getValue());
        int n = commissionProductMapper.updateByPrimaryKeySelective(commissionProductQo);

        //指定产品配置id
        Weekend<CommissionRole> weekend = Weekend.of(CommissionRole.class);
        WeekendCriteria<CommissionRole, Object> criteria = weekend.weekendCriteria();
        criteria.andEqualTo(CommissionRole::getComProdId, id);
        //删除标识为is
        CommissionRole updateCommissionRole = new CommissionRole();
        updateCommissionRole.setIsDeleted(IsDeletedEnum.IS.getValue());
        n += commissionRoleMapper.updateByExampleSelective(updateCommissionRole, weekend);
        return n;
    }

    @Override
    public ResponseEntity queryCommissionPushListVO(CommissionPushQO commissionPushQO) {

        CommissionPushCountVO commissionPushCountVO = commissionPushMapper.selectCommissionPushListCount(commissionPushQO);
        if (null == commissionPushCountVO || commissionPushCountVO.getTotal() == 0) {
            return GenericDataResponse.errorWithMsg("无查询信息!");
        }
        List<CommissionPush> commissionPushes = commissionPushMapper.selectCommissionPushList(commissionPushQO);

        return GenericDataResponse.okWithData(new CommissionPushListVO(commissionPushCountVO, commissionPushes));
    }

    @Override
    public ResponseEntity<GenericListResponse<CommissionPush>> downCommissionPushListVO(CommissionPushQO commissionPushQO) {

        CommissionPushCountVO commissionPushCountVO = commissionPushMapper.selectCommissionPushListCount(commissionPushQO);
        if (null == commissionPushCountVO || commissionPushCountVO.getTotal() == 0) {
            GenericListResponse.listNoCount(null);
        }
        List<CommissionPush> commissionPushes = commissionPushMapper.selectCommissionPushList(commissionPushQO);
        return GenericListResponse.listAndCount(commissionPushes, Long.valueOf(commissionPushCountVO.getTotal()));

    }

    /**
     * 计算佣金生产推送信息
     *
     * @param logId          日志跟踪标识
     * @param appDetailProVo 投保单详情
     * @param endorsementNo  批单时的批单号
     * @param premium        保费
     * @param issureDate     出单时间
     * @return
     */
    private CommissionPush calCommissionCreatePush(String logId, AppDetailProVo appDetailProVo, String endorsementNo,
                                                   BigDecimal premium, Date issureDate) {
        if (CollectionUtils.isEmpty(appDetailProVo.getAgents())) {
            //没有推广人 不处理
            log.info("{} 投保单号：{}没有推广人，不做佣金处理。", logId, appDetailProVo.getApplicationFormCode());
            return null;
        }
        String userCode = appDetailProVo.getAgents().get(0).getAgentCode();
        //查询营销人员信息表
        MarketerInfoEntity marketerInfoEntity = new MarketerInfoEntity();
        marketerInfoEntity.setUserCode(userCode);
        marketerInfoEntity.setIsDeleted(false);
        //查询列表 正常只会有一条记录
        List<MarketerInfoEntity> marketerInfos = marketerInfoMapper.select(marketerInfoEntity);
        if (CollectionUtils.isEmpty(marketerInfos)) {
            log.info("{} 投保单号：{}, 推广人不是营销员，不做佣金处理。", logId, appDetailProVo.getApplicationFormCode());
            if ("02".equals(appDetailProVo.getChannelType())) {
                log.info("{} 投保单号：{}, 产品编号:{},为我学保产品，记录内部推广业绩。", logId, appDetailProVo.getApplicationFormCode(), appDetailProVo.getProductCode());
                //不是营销员 就是内部员工 创建内部员工业绩
                insertInsidePerformance(logId, appDetailProVo, endorsementNo, premium, issureDate);
            }
            return null;
        }
        MarketerInfoEntity marketerInfo = marketerInfos.get(0);
        MarketerRoleEnum marketerRole = MarketerRoleEnum.getMarketerRoleEnumByCode(marketerInfo.getRoleCode());
        CommissionVO commissionVO = selectCommission(appDetailProVo.getProductCode(), marketerRole);
        if (null == commissionVO) {
            //没有佣金产品角色配置信息
            log.error("{} 投保单号：{}, 该产品编码{}没有配置佣金产品及角色信息，不做佣金处理。", logId, appDetailProVo.getApplicationFormCode(), appDetailProVo.getProductCode());
            return null;
        }

        return createCommissionPush(logId, marketerInfo, commissionVO, marketerRole, appDetailProVo, endorsementNo, premium, issureDate);
    }

    /**
     * 我学保-记录内部员工业绩
     *
     * @param logId
     * @param appDetailProVo
     * @param endorsementNo
     * @param premium
     * @param issureDate
     */
    private void insertInsidePerformance(String logId, AppDetailProVo appDetailProVo, String endorsementNo, BigDecimal premium, Date issureDate) {
        String userCode = appDetailProVo.getHolder().getHolderCode();

        if (StringUtils.isBlank(userCode)) {
            log.info("{} 投保单号：{} 被推广人:userCode 为空，不做处理。", logId, appDetailProVo.getApplicationFormCode());
        }

        //获取该用户当前推广人
        Weekend<RegisterCustomer> weekend = Weekend.of(RegisterCustomer.class);
        WeekendCriteria<RegisterCustomer, Object> criteria = weekend.weekendCriteria();
        criteria.andEqualTo(RegisterCustomer::getCustomerCode, userCode);
        criteria.andEqualTo(RegisterCustomer::getIsDeleted, false);
        List<RegisterCustomer> registerCustomers = registerCustomerMapper.selectByExample(weekend);
        //校验推广人是否过期 且与保单记录的推广人是否是同一个人
        if (CollectionUtils.isEmpty(registerCustomers)) {
            log.info("{} 投保单号：{} 被推广人:userCode 无推广人。", logId, appDetailProVo.getApplicationFormCode(), userCode);
            return;
        }
        RegisterCustomer registerCustomer = registerCustomers.get(0);
//        if(!(registerCustomer = registerCustomers.get(0)).getUserCode().equals(appDetailProVo.getAgents().get(0).getAgentCode())) {
//            log.info("{} 投保单号：{} 保单推广人：{}与该用户在推广人信息表记录的推广人：{}不一致,不记录业绩!"
//                    , logId, appDetailProVo.getApplicationFormCode(), appDetailProVo.getAgents().get(0).getAgentCode(), registerCustomers.get(0).getUserCode());
//            return;
//        }
        String policyStatus;
        if (StringUtils.isEmpty(endorsementNo)) {
            policyStatus = PerformancePolicyStatusEnum.INSURED.getStatus();
        } else {
            policyStatus = PerformancePolicyStatusEnum.CANCELLATION.getStatus();
            //退保时 查询之前业绩表中是否有数据
            InsidePerformance oldInsidePerformance = insidePerformanceService.queryInsidePerformanceByPolicyNo(appDetailProVo.getPolicyNo());
            //如果有更新保单状态 否则插入
            if (oldInsidePerformance != null) {
                InsidePerformance insidePerformance = new InsidePerformance();
                insidePerformance.setId(oldInsidePerformance.getId());
                insidePerformance.setUpdateTime(new Date());
                insidePerformance.setPolicyStatus(policyStatus);
                insidePerformanceMapper.updateByPrimaryKeySelective(insidePerformance);
                return;
            }
        }

        //大佣金比例*35%/1.06  就是内部人员的奖励
        CommissionVO commission = selectCommission(appDetailProVo.getProductCode(), MarketerRoleEnum.ROLE_00);
        if (null == commission) {
            //没有佣金产品角色配置信息
            log.error("{} 投保单号：{}, 该产品编码{}没有配置佣金产品不做处理。", logId, appDetailProVo.getApplicationFormCode(), appDetailProVo.getProductCode());
            return;
        }

        BigDecimal commissionPremium = premium.multiply(new BigDecimal(0.3)).multiply(commission.getComProdAcc()).divide(new BigDecimal(1.06), 5, BigDecimal.ROUND_HALF_UP);
        log.info("{} 投保单号：{}, 该产品编码{} 推广人业绩计算结果。{}", logId, appDetailProVo.getApplicationFormCode(), appDetailProVo.getProductCode(), commissionPremium);


        InsidePerformance insidePerformance = new InsidePerformance();
        insidePerformance.setManagerName(registerCustomer.getManagerName());
        insidePerformance.setManagerAccount(registerCustomer.getManagerAccount());
        insidePerformance.setBranchCode(registerCustomer.getBranchCode());
        insidePerformance.setBranchName(registerCustomer.getBranchName());
        insidePerformance.setPolicyNo(appDetailProVo.getPolicyNo());
        insidePerformance.setProductCode(appDetailProVo.getProductCode());
        insidePerformance.setProductName(appDetailProVo.getProductName());
        insidePerformance.setIssureDate(issureDate);
        //只有我学保记录业绩，我学保投保人都是个人
        insidePerformance.setHolderName(appDetailProVo.getHolder().getHuman().getName());
        insidePerformance.setHolderPhone(appDetailProVo.getHolder().getHuman().getPhone());
        //如果批单号为空 表示保单状态是出单  否则退保
        insidePerformance.setPolicyStatus(policyStatus);
        insidePerformance.setStartTime(DateUtils.str2Date(appDetailProVo.getStartDate(), DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        insidePerformance.setEndTime(DateUtils.str2Date(appDetailProVo.getEndDate(), DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        insidePerformance.setPremium(premium);
        //推荐奖励
        insidePerformance.setPerformance(commissionPremium);
        insidePerformance.setCreateTime(new Date());
        insidePerformance.setUpdateTime(new Date());
        insidePerformance.setIsDeleted(IsDeletedEnum.NO.getValue());
        insidePerformanceMapper.insertSelective(insidePerformance);
        log.info("{} 投保单号：{}, 该产品编码{} 内部人员业绩插入完成。", logId, appDetailProVo.getApplicationFormCode(), appDetailProVo.getProductCode());

    }

    /*
}*
     * 通过投保单号 得到投保单详情
     * @param appCode
     * @return
     */
    private AppDetailProVo searchAppDetailPro(String appCode) {
        AppDetailProParam appDetailProParam = new AppDetailProParam();
        appDetailProParam.setAppCode(appCode);
        // 渠道编号
        appDetailProParam.setChannelCode("edu");
        ResponseEntity<GenericDataResponse<AppDetailProVo>> appDetailPro;
        AppDetailProVo detailVos = null;
        try {
            appDetailPro = insClient.searchAppDetailPro(appDetailProParam);
            detailVos = appDetailPro.getBody().getData();
        } catch (Exception e) {
            log.error("投保单号：{}查询投保单信息失败，出错原因：{}", appCode, e.getMessage());
        }
        return detailVos;
    }

    /**
     * 查询产品角色配置-当是地区产品的组员 角色时 返回组长配置信息
     *
     * @param productCode
     * @param marketerRole 角色
     * @return
     */
    private CommissionVO selectCommission(String productCode, MarketerRoleEnum marketerRole) {
        CommissionQO commissionQO = new CommissionQO();
        commissionQO.setProductCode(productCode);
        commissionQO.setRoleCode(marketerRole.getCode());
        //查询该角色对应的产品佣金配置信息
        //正常只会存在一条记录
        List<CommissionVO> commissions = commissionMapper.selectCommissionList(commissionQO);
        if (CollectionUtils.isEmpty(commissions)) {
            //该产品没有佣金配置信息 或没有该角色的佣金配置信息
            return null;
        }
        //如果是组员角色，且该产品配置的组员佣金比例都为0
        CommissionVO commission = commissions.get(0);
        if (MarketerRoleEnum.ROLE_03.equals(marketerRole)
                && BigDecimal.ZERO.compareTo(commission.getBrokerAcc()) == 0
                && BigDecimal.ZERO.compareTo(commission.getDepartmentAcc()) == 0
                && BigDecimal.ZERO.compareTo(commission.getBranchOfficeAcc()) == 0
                && BigDecimal.ZERO.compareTo(commission.getHeadOfficeAcc()) == 0) {
            //查询组长的佣金比例
            commissionQO.setRoleCode(MarketerRoleEnum.ROLE_02.getCode());
            commissions = commissionMapper.selectCommissionList(commissionQO);
            if (CollectionUtils.isEmpty(commissions)) {
                //该产品没有佣金配置信息 或没有该角色的佣金配置信息
                return null;
            }
            return commissions.get(0);
        }
        return commission;
    }

    /**
     * 创建佣金推送对象
     *
     * @param logId
     * @param marketerInfo   营销员
     * @param commission     营销员佣金配置
     * @param marketerRole   角色
     * @param appDetailProVo 保单详情
     * @param endorsementNo
     * @param premium
     * @return
     */
    private CommissionPush createCommissionPush(String logId, MarketerInfoEntity marketerInfo, CommissionVO commission, MarketerRoleEnum marketerRole,
                                                AppDetailProVo appDetailProVo, String endorsementNo, BigDecimal premium, Date issureDate) {
        CommissionPush commissionPush = new CommissionPush();
        commissionPush.setProductCode(commission.getProductCode());
        commissionPush.setProductName(commission.getProductName());
        commissionPush.setComProdAcc(commission.getComProdAcc());
        commissionPush.setIsIncludeTax(commission.getIsIncludeTax());
        commissionPush.setRoleCode(marketerRole.getCode());
        commissionPush.setRoleName(marketerRole.getMsg());
        commissionPush.setBrokerAcc(commission.getBrokerAcc());
        commissionPush.setDepartmentAcc(commission.getDepartmentAcc());
        commissionPush.setBranchOfficeAcc(commission.getBranchOfficeAcc());
        commissionPush.setHeadOfficeAcc(commission.getHeadOfficeAcc());
        commissionPush.setMarketerNo(marketerInfo.getMarketerNo());
        commissionPush.setPolicyNo(appDetailProVo.getPolicyNo());
        commissionPush.setEndorsementNo(endorsementNo);
        commissionPush.setPremium(premium);
        commissionPush.setIssureDate(issureDate);
        //投保人
        String holderName;
        //判断是企业还是个人
        if ("00".equals(appDetailProVo.getHolder().getType())) {
            holderName = appDetailProVo.getHolder().getCorporation().getName();
        } else {
            holderName = appDetailProVo.getHolder().getHuman().getName();
        }
        //被保人
        String insuredName = "";
        if ("00".equals(appDetailProVo.getInsuredList().get(0).getType())) {
            //企业只会有一个
            insuredName = appDetailProVo.getInsuredList().get(0).getCorporation().getName();
        } else {
            for (InsuredForProVO insuredForProVOS : appDetailProVo.getInsuredList()) {
                if (StringUtils.isBlank(insuredName)) {
                    insuredName = insuredName + insuredForProVOS.getHuman().getName();
                } else {
                    insuredName = insuredName + "/" + insuredForProVOS.getHuman().getName();
                }
            }
        }
        commissionPush.setHolderName(holderName);
        commissionPush.setInsuredName(insuredName);
        commissionPush.setChannelCode(marketerInfo.getChannelCode());
        commissionPush.setChannelName(marketerInfo.getChannelName());
        commissionPush.setMarketerName(marketerInfo.getMarketerName());
        commissionPush.setMarketerPhone(marketerInfo.getMarketerPhone());
        commissionPush.setBranchCode(marketerInfo.getBranchCode());
        commissionPush.setBranchName(marketerInfo.getBranchName());
        //增加营销员增员渠道快照信息
        commissionPush.setAddChannelCode(marketerInfo.getAddChannelCode());
        commissionPush.setAddChannelName(marketerInfo.getAddChannelName());
        //增加推荐人信息
        commissionPush.setReferrerName(marketerInfo.getReferrerName());
        commissionPush.setReferrerCode(marketerInfo.getReferrerCode());
        commissionPush.setReferrerPhone(marketerInfo.getReferrerPhone());
        commissionPush.setReferrerBranchCode(marketerInfo.getReferrerBranchCode());
        commissionPush.setReferrerBranchName(marketerInfo.getReferrerBranchName());
        //查询营销员员工 小队信息
        List<CommissionTeamVO> commissionTeamVOS = teamService.queryTeamByMarketerNo(marketerInfo.getMarketerNo(), YesOrNoEnum.NO);
        log.error("{} 通过员工编号：{} 查询营销员员工小队信息结果->{}。", logId, marketerInfo.getMarketerNo(), JSON.toJSONString(commissionTeamVOS));
        //正常最多只会存在一个小队信息
        if (CollectionUtils.isNotEmpty(commissionTeamVOS)) {
            CommissionTeamVO commissionTeamVO = commissionTeamVOS.get(0);
            commissionPush.setTeamId(commissionTeamVO.getTeamId());
            commissionPush.setTeamName(commissionTeamVO.getTeamName());
            commissionPush.setTeamFounderId(commissionTeamVO.getTeamFounderId());
            commissionPush.setFounderNo(commissionTeamVO.getFounderNo());
            commissionPush.setFounderName(commissionTeamVO.getFounderName());
        }

        //todo  如果营销员是教育专属 推荐奖励给他的推荐人（如果这个推荐人是营销员，）
        //含税佣金
        BigDecimal commissionPremium = premium.multiply(commission.getComProdAcc()).divide(new BigDecimal(1.06), 5, BigDecimal.ROUND_HALF_UP);
        //如果不含税 再除以1.06
        if (IsOrNotEnum.not(commission.getIsIncludeTax())) {
            commissionPremium = commissionPremium.divide(new BigDecimal(1.06), 5, BigDecimal.ROUND_HALF_UP);
        }
        //去掉百分比并四舍五入保留两位小数
        commissionPremium = commissionPremium.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);

        //营销人员佣金
        BigDecimal brokerFyc = commissionPremium.multiply(commission.getBrokerAcc()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
        //部门管理费
        BigDecimal departmentFee = commissionPremium.multiply(commission.getDepartmentAcc()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
        //分公司管理费
        BigDecimal branchOfficeFee = commissionPremium.multiply(commission.getBranchOfficeAcc()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
        //总部利润
        BigDecimal headOfficeFee = commissionPremium.subtract(brokerFyc).subtract(departmentFee).subtract(branchOfficeFee);


        //如果是组员 且配置信息是组长的配置信息表示需要指定营销人员
        if (MarketerRoleEnum.ROLE_03.equals(marketerRole)
                && MarketerRoleEnum.ROLE_02.getCode().equals(commission.getRoleCode())) {
            commissionPush.setBrokerFyc(BigDecimal.ZERO);
            commissionPush.setSpecialType(SpecialTypeEnum.IS.getCode());
            commissionPush.setFixedAgentCode(marketerInfo.getLeaderCode());
            commissionPush.setFixedAgentName(marketerInfo.getLeaderName());
            commissionPush.setFixedMoney(brokerFyc);
        } else {
            commissionPush.setBrokerFyc(brokerFyc);
        }
        commissionPush.setDepartmentFee(departmentFee);
        commissionPush.setBranchOfficeFee(branchOfficeFee);
        commissionPush.setHeadOfficeFee(headOfficeFee);

        return commissionPush;
    }


    @Override
    public MarketerUserRoleBO queryCommissionRole(String userCode) throws Exception {
        //得到营销角色及小队，创始人信息
        MarketerUserRoleVo marketerUserRoleVo = teamFounderMapper.selectMarketerRoleByUserCode(userCode);
        //判断营销角色
        MarketerUserRoleEnum marketerUserRoleEnum = getMarketerUserRoleEnumByMarketerRoleVo(marketerUserRoleVo);

        MarketerUserRoleBO marketerUserRoleBO = new MarketerUserRoleBO();
        marketerUserRoleBO.setMarketerUserRole(marketerUserRoleEnum.getUserRoleCode());

        //角色信息
        marketerUserRoleBO.setUserRoleCode(marketerUserRoleEnum.getUserRoleCode());

        //营销员
        if (MarketerUserRoleEnum.SALESMAN.equals(marketerUserRoleEnum)) {
            marketerUserRoleBO.setMarketerNo(marketerUserRoleVo.getMarketerNo());
            marketerUserRoleBO.setMarketerName(marketerUserRoleVo.getMarketerName());
        }
        //营销小队队长
        if (MarketerUserRoleEnum.LEADER.equals(marketerUserRoleEnum)) {
            TeamMembersQO teamMembersQO = new TeamMembersQO();
            teamMembersQO.setTeamId(marketerUserRoleVo.getTeamId());
            List<TeamMembersVO> teamMembersVOS = teamFounderMapper.queryTeamMembersDetail(teamMembersQO);
            marketerUserRoleBO.setTeamMembersVOS(teamMembersVOS);
            //添加小队信息
            TeamVo teamVo = new TeamVo();
            teamVo.setTeamId(marketerUserRoleVo.getTeamId());
            teamVo.setTeamName(marketerUserRoleVo.getTeamName());
            marketerUserRoleBO.setTeams(Lists.newArrayList(teamVo));

            //添加团队信息
            FounderVo founderVo = new FounderVo();
            founderVo.setTeamFounderId(marketerUserRoleVo.getTeamFounderId());
            founderVo.setTeamFounderName(marketerUserRoleVo.getTeamFounderName());
            marketerUserRoleBO.setFounders(Lists.newArrayList(founderVo));
        }

        //创始人
        if (MarketerUserRoleEnum.FOUNDER.equals(marketerUserRoleEnum)) {
            TeamMembersQO teamMembersQO = new TeamMembersQO();
            teamMembersQO.setTeamFounderId(marketerUserRoleVo.getTeamFounderId());
            List<TeamMembersVO> teamMembersVOS = teamFounderMapper.queryTeamMembersDetail(teamMembersQO);
            marketerUserRoleBO.setTeamMembersVOS(teamMembersVOS);

            //添加团队信息
            FounderVo founderVo = new FounderVo();
            founderVo.setTeamFounderId(marketerUserRoleVo.getTeamFounderId());
            founderVo.setTeamFounderName(marketerUserRoleVo.getTeamFounderName());
            marketerUserRoleBO.setFounders(Lists.newArrayList(founderVo));
        }

        //管理人员
        if (MarketerUserRoleEnum.MANAGER.equals(marketerUserRoleEnum)) {


            List<BranchVO> branchVOS = Lists.newArrayList();
            // 权限设置
            try {
                List<String> branchCodes = Lists.newArrayList();
                ResponseEntity<GenericDataResponse<Map<String, Object>>> responseEntity = userClient.queryUserRoleAndAuthority(userCode, "sys_edu_man");

                LinkedHashMap<String, String> map = (LinkedHashMap) responseEntity.getBody().getData().get("dataPopedom");
                String jtBranchs = map.get("jtBranchs");
                log.debug("{} 导出创始人信息 用户中心返回值 jtBranchs = {}", jtBranchs);

                if (!"000000".equals(jtBranchs) && !"JT0000".equals(jtBranchs)) {//非全国
                    String jtBranchCode = (String) responseEntity.getBody().getData().get("jtBranchCode");
                    String jtBranchName = (String) responseEntity.getBody().getData().get("jtBranchName");

                    branchVOS.add(new BranchVO(jtBranchCode, jtBranchName));
                    if (StringUtils.isNotBlank(jtBranchs)) {
                        for (String b : jtBranchs.split(",")) {
                            branchCodes.add(b);
                            GenericListResponse<JtBranchInfoVo> result = userClient.queryThirdGradeBranch(b);
                            if (null != result && result.getTotal() > 0) {
                                for (JtBranchInfoVo jtBranchInfoVo : result.getList()) {
                                    branchVOS.add(new BranchVO(jtBranchInfoVo.getCode(), jtBranchInfoVo.getJtBranchName()));
                                }
                            }
                        }
                    }
                }
                marketerUserRoleBO.setBranches(branchVOS);
                marketerUserRoleBO.setFounders(teamService.queryTeamFoundersByBranchCode(String.join(",", branchCodes)));
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("用户权限查询异常!");
            }
        }
        return marketerUserRoleBO;
    }

    /**
     * 通过营销员信息 业务查询时用户的营销角色权限
     *
     * @param marketerUserRoleVo
     * @return
     */
    private MarketerUserRoleEnum getMarketerUserRoleEnumByMarketerRoleVo(MarketerUserRoleVo marketerUserRoleVo) {
        if (null == marketerUserRoleVo) {
            return MarketerUserRoleEnum.MANAGER;
        }
        if (null != marketerUserRoleVo.getTeamFounderId()) {
            return MarketerUserRoleEnum.FOUNDER;
        }
        if (null != marketerUserRoleVo.getTeamId()) {
            return MarketerUserRoleEnum.LEADER;
        }
        return MarketerUserRoleEnum.SALESMAN;
    }
}
